package io.spring.nn.controller;

import com.sun.org.apache.xpath.internal.objects.XString;
import io.spring.nn.bean.Review;
import io.spring.nn.bean.User;
import io.spring.nn.mapper.UserMapper;
import org.apache.catalina.filters.ExpiresFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.HttpSessionRequiredException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;
import javax.swing.*;
import java.util.List;

@Controller
public class LoginController {

    @Autowired
    UserMapper userMapper;

    @GetMapping("/main")
    public String coo(HttpSession session){
        User user = (User) session.getAttribute("user");
        List<Review> getcontent = userMapper.getcontent(user.getId());
        session.setAttribute("getcontent", getcontent);
        return "usercenter";
    }

    @PostMapping("/login")
//    @ResponseBody
    public String login(@RequestParam("username") String name,
                        @RequestParam("password") String password,
                        HttpSession session) {

        List<User> all = userMapper.getAll();

        for (User item : all){
            if (name.equals(item.getUsername())){
                if (password.equals(item.getPassword())) {
                    User user = userMapper.getUser(name);
                    session.setAttribute("user", user);
                    List<Review> getcontent = userMapper.getcontent(user.getId());
                    session.setAttribute("getcontent", getcontent);


                    return "usercenter";
                }
            }
        }
        //JOptionPane.showMessageDialog(null,"登录失败，用户名或密码错误！");
        session.setAttribute("err","用户名或密码错误");

        return "login";
    }

    @PostMapping("/logup")
    public String logup(User user) {


        userMapper.insertUser(user);

        return "login";
    }

    @PostMapping("/revise")
    public String revise(User user,HttpSession session ) {
        User user1 = (User) session.getAttribute("user");

        user.setUsername(user1.getUsername());
        userMapper.updateUser(user);
        user = userMapper.getUser(user.getUsername());
        session.setAttribute("user",user);

        return "redirect:/usercenter.html";
    }

    @PostMapping("/w_content")
    public String w_content(@RequestParam("con") String content,
                            HttpSession session) {
        User user = (User) session.getAttribute("user");
        userMapper.insertContent(content,user.getId());
//        return "forward:/login?username="+user.getUsername(),;
        return "redirect:/main";

    }

}
